<?php

namespace app\admin\controller;

use app\admin\model\Menu;
use think\facade\View;
use app\admin\service\MenuService;
use think\exception\ValidateException;

class MenuController extends BaseController
{
    public function index()
    {   
        $menuService = new MenuService();
        $list = $menuService->getMenuList();

        return View::fetch('',['list' => $list]);
    }

    public function create()
    {
        $menuService = new MenuService();
        $menuOption = $menuService->getMenuOption();

        return View::fetch('',['menuOption' => $menuOption]);   
    }

    public function child()
    {   
        $parent_id = $this->request->param('id/d'); 

        $menuService = new MenuService();
        $menuOption = $menuService->getMenuOption();

        return View::fetch('',['menuOption' => $menuOption,'parent_id' => $parent_id]);   
    }

    public function edit()
    {   
        $id = $this->request->get('id/d');
        $menuService = new MenuService();
        $options = $menuService->getMenuOption();
        $row = $menuService->findMenu($id);

        return View::fetch('',['options' => $options, 'row' => $row]);   
    }

    public function save()
    {
        $param = $this->request->post();

        try{
            validate('MenuValidate')->check($param);
        } catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
      

        $model = Menu::create($param);

        return !empty($model['id']) ? json(['code' => 1, 'msg' => '保存成功!']) : json(['code' => 0, 'msg' => '保存失败!']);
    
    }

    public function switch()
    {
        $param = $this->request->post();

        try {
            validate('MenuValidate.switch')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        Menu::update($param);

        return json(['code' => 1, 'msg' => '更新成功!']);
    }

    public function update()
    {
        $param = $this->request->post();

        try{
            validate('MenuValidate.edit')->check($param);
        } catch (ValidateException $e){
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
        
        $model = Menu::update($param);

        return  json(['code' => 1, 'msg' => '更新成功!']);
    }


    public function delete()
    {
        $id = $this->request->get('id',0);
        
        $result = Menu::destroy($id);

        return $result ? json(['code' => 1, 'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败!']);
    }
}